String.format = function(str) {
    var args = arguments, re = new RegExp("%([1-" + args.length + "])", "g");
    return String(str).replace(
        re,
        function($1, $2) {
            return args[$2];
        }
    );
};

var Util = {};

//标签控制
Util.Layer = (function(){
    var _cache = {},Return = {};	//缓存类
	
    //最小化
    Return.Min = function(box,mBox,callback){
        if(!_cache.MinBorder){
            _cache.Minborder = $('<div style="z-index:10000000;background: none repeat scroll 0 0 #fff;filter:alpha(opacity=30);-moz-opacity:0.3;opacity:0.3;border:1px soild #ccc;position:absolute;top:0;left0;display:none;"></div>');
            $(document.body).append(_cache.Minborder);
        }
        //mBox.show();
        var w = box.width(), h = box.height(), t = box.offset().top, l = box.offset().left, eT = mBox.offset().top, eL = mBox.offset().left, eW = mBox.width(), eH = mBox.height();
        _cache.Minborder.width(w).height(h).css({
            left:l,
            top:t
        }).show();
        _cache.Minborder.animate({
            width:eW,
            height:eH,
            top:eT,
            left:eL
        },300,function(){
            _cache.Minborder.hide();
        });

        if(callback){
            callback();
        }
    }
	
    /*
	设置标签居中(左右居中，上下1:2)
	
	*/
    Return.Center = function(box,setting){
        var mainBox;
        var cut = 0, t = 0, l = 0;
        if(setting){
            if(setting.Main){
                mainBox = setting.Main;
                t = mainBox.offset().top;
                l = mainBox.offset().left;
            }
            else{
                mainBox = $(window);
            }
            if(setting.Cut != undefined){
                cut = setting.Cut;
            }
        }
        else{
            mainBox = $(window);
        }
		
        var cssT = (mainBox.height() - box.height())/3 + cut + t;
        var cssL = (mainBox.width() - box.width())/2 + cut + l;
        if(cssT < 0){
            cssT = 0;
        }
        if(cssL < 0){
            cssL = 0;
        }
        var st = mainBox.scrollTop();
        if(st){
            cssT += st;
        }
        box.css({
            top: cssT, 
            left: cssL
        });
    }
		
    return Return;
})();

(function($,w){
    var record_id = null,record_dom = $('.note-book');
    $('#easynote-home').on('click','#js-note-list li .record-item',function(e){
        //获取记事
        hideBookMenu();
        record_id = $(this).closest('li').attr('record_id');
        $.getJSON(record_dom.data('url'),{record_id:record_id},renderRecord);
    }).on('click','#js-note-list li.note-list-none',function(e){
        $('.record-title').focus();
    }).on('keydown','#js-content',function(e){
        //保存
        if((e.keyCode==13||e.keyCode==83)&& e.ctrlKey)
        {
            $('#js-editSave').click();
            return false;
        }
    }).on('click','#js-editSave',function(e){
        //保存
        action = record_dom.data('action');
        title = record_dom.find('.record-title').val();
        content = record_dom.find('.book-center #js-content').val();
        book_id = record_dom.find('#js-cate-menu ul li i.i-done').closest('#js-cate-menu ul li').attr('book_id');
        geo_address = '';
        $.post(
            $(this).data('url'),
            {action:action,id:record_id,title:title,content:content,book_id:book_id,geo_address:geo_address},
            renderResult,
            'json'
        );
        return false;
    }).on('click','#js-cate-name',function(e){
        //点击头部分类
        if($('#js-cate-menu').data('display') == 'show'){
            $('#js-cate-menu').fadeOut();
            $('#js-cate-menu').data('display','hide')
        }else{
            $('#js-cate-menu').fadeIn();
            $('#js-cate-menu').data('display','show')
        }
    }).on('click','#js-pager a',function(e){
        //点击分页
        url = $(e.currentTarget).data('url');
        $.getJSON(url,function(json){
            renderList(json.records);
            $('#js-pager a').removeClass('focus');
            $(e.currentTarget).addClass('focus');
        });
    }).on('click','#js-cate-menu li',function(e){
        hideBookMenu();
        $.post(
            $('#js-cate-menu').data('url'),
            {book_id:$(this).attr('book_id'),id:record_id},
            function(json){},
            'json'
        );
        changeRecordMenu(this);
    }).on('click','#js-cate-list li.custom-cate-getlist,#js-cate-list li#js-type-all',function(e){
        book_id = $(this).attr('book_id');
        hideBookMenu();
        clearRecordRect();
        if(book_id == 'default' || book_id == 'all'){
            changeRecordMenu($('#js-cate-menu ul li[book_id=0]'));
        }else{
            changeRecordMenu($('#js-cate-menu ul li[book_id='+book_id+']'));
        }
        _this = $(this);
        $.getJSON(
            $('#js-note-list').data('url'),
            {book_id:book_id},
            function(json){
                p_h = '',v = {};
                $('#js-cate-list').find('i.ico-menu').removeClass('i-done');
                _this.find('i.ico-menu').addClass('i-done');
                if(json.records == '') {
                    $('#js-note-list').empty();
                    $('#js-note-list').html(formatTemplate($("#jstpl-notelist-null").html(),{msg:'当前没有记事<br />赶紧写一个吧'}));
                    $('#js-pager').empty();
                    return false;
                }
                renderList(json.records);
                renderPager($('#js-note-list').data('url')+'/book_id/'+book_id,json.pageCount);
            }
        );
    }).on('click','#js-cate-list li.cate-important',function(e){
        hideBookMenu();
        clearRecordRect();
        _this = $(this);
        $.getJSON(_this.data('url'),function(json){
            p_h = '',v = {};
            $('#js-cate-list').find('i.ico-menu').removeClass('i-done');
            _this.find('i.ico-menu').addClass('i-done');
            if(json.records == '') {
                $('#js-note-list').empty();
                $('#js-note-list').html(formatTemplate($("#jstpl-notelist-null").html(),{msg:'当前没有记事<br />赶紧写一个吧'}));
                $('#js-pager').empty();
                return false;
            }
            renderList(json.records);
            renderPager(_this.data('url'),json.pageCount);
        })
    }).on('click','#js-addType',function(){
        var li=$("#js-cate-list").find("li.js_isnew");
        if(li.length==0){
            li = $(formatTemplate($("#jstpl-typelist-item").html(),{book_id:0, name:"",count:0}));
            $("#js-cate-list .add-cate").before(li);
            changeTypeEditMode(li.addClass("js_isnew"));
        }
        li.children("input").focus();
        return false;
    }).on("click","#js-cate-list .edit",function(){ //转编辑模式
            li = $(this).parents("li");
            changeTypeEditMode(li,li.children('em').remove('span').html());
            return false;
    }).on('click','#js-cate-list .save',function(e){
        var li = $(this).closest('li');
        name = li.children('input').val();
        if(name.length>15){
            warningTip('分类名称不能超过15个字符');
            return false;
        }
        $.getJSON($('#js-cate-list').data('save-url'),{book_id:li.attr('book_id'),name:li.children('input').val()},function(json){
            if(json){
                changeTypeDefMode(li.removeClass("js_isnew"),li.children('input').val(),li.find('em span').html());
            }else
                return false;
        });
    })

    function changeTypeDefMode(li,name,count){
        li.removeClass("hover").children("a").eq(0).show().children("em").attr("t_title", name).html(name+"(<span>"+ count +"</span>)").end().next().hide().val("").next().addClass("edit").removeClass("save");
    }

    function changeTypeEditMode(li,name){
        li.addClass("hover").children("a").eq(0).hide().next().show().val(name||"").next().addClass("save").removeClass("edit");
    }

    function renderPager(root_url,page_count){
        for(var i=1;i<=page_count;i++){
            v.url = root_url+'/page/'+i;
            v.page = i;
            v.focus = i == '1'?'class="focus"':'';
            p_h = p_h+formatTemplate($("#jstpl-notepage-item").html(),v);
        }
        $('#js-pager').empty().html(p_h);
    }

    function clearRecordRect(remenu){
        record_dom.attr('data-action','create');
        if(remenu) changeRecordMenu($('#js-cate-menu ul li[book_id=0]'));
        $('#js-create_time').html('创建时间:现在');
        $('#js-update_time').empty();
        $('.record-title').val('');
        $('#js-content').val('');
    }

    function changeRecordMenu(t){
        $('#js-cate-menu ul li').find('i').removeClass('i-done');
        $(t).find('i').addClass('i-done');
        $('em#js-cate-name').text($(t).attr('title'));
    }
    
    //渲染单个记事
    function renderRecord(record){
        //标记记事内容为update
        record_dom.attr('data-action','update');
        //记事本
        $('#js-cate-menu ul li').find('i').removeClass('i-done');
        if(!record.book_id){
            changeRecordMenu($('i','#js-cate-menu li:first-child'));
        }else{
            changeRecordMenu($('#js-cate-menu ul li[book_id='+record.book_id+']'));
        }

        //创建及更新时间
        $('#js-create_time.create-time').text("创建时间:"+formatDateTime(new Date(record.created*1000)));
        $('#js-update_time.update-time').text("更新时间:"+formatDateTime(new Date(record.updated*1000)));
        //标题
        $('.book-center .record-title').val(record.title);
        //内容
        $('.book-center #js-content').val(record.content);
        //复制，删除

    }

    //清除记事本菜单
    function hideBookMenu(){
        $('#js-cate-menu').hide();
        $('#js-cate-menu').data('display','hide')
    }
    
    //渲染记事列表
    function renderList(list){
        h = '';
        $.each(list,function(i,v){
            v.isdisplay = v.has_notice == '1'?"display:block":"display:none";
            v.date = formatDateCheckYear(v.updated);
            v.marked = v.has_star == '1'?'marked':'';
            if(!v.title) v.title = '无标题';
            h = h+formatTemplate($("#jstpl-notelist-item").html(),v);
        });
        $('#js-note-list').empty();
        $('#js-note-list').html(h);
    }
    
    //保存结果
    function renderResult(json){
        h = '';
        if(json.action == 'create' && !!json.id){
            h = getRecordHtml(json);
            $('#js-note-list').prepend(h);
        }else if(json.action == 'update' && json.result){
            replaceRecord = $('#js-note-list li[record_id='+json.id+']');
            time = formatDateCheckYear(json.updated);
            replaceRecord.find('.til').html(json.title);
            replaceRecord.find('.time').html(time);
            //geo_address
        }
    }

    function getRecordHtml(record){
        clearRecordRect(false);
        record.isdisplay = record.has_notice == '1'?"display:block":"display:none";
        record.date = formatDateCheckYear(record.updated);
        record.marked = record.has_star == '1'?'marked':'';
        if(!record.title) record.title = '无标题';
        return formatTemplate($("#jstpl-notelist-item").html(),record);
    }

    function formatDateCheckYear(date){
        date = new Date(date*1000);
        if(date.getFullYear() == (new Date).getFullYear())
            return formatDate(date,'MM-dd');
        else
            return formatDate(date,'yyyy-MM-dd');
    }

    function formatDateTime(date){
        var now=window.CURR_TIME||new Date(),format="yyyy-MM-dd",dev,
            ch=["零","一","二","三","四","五","六","七","八","九","十"];
        now=new Date(now.getFullYear(),now.getMonth(),now.getDate())
        function fix(num,fx,ad){
            var m=num%fx;
            return (num-m)/fx + (m?ad||0:0);
        }
        if(formatDate(now,format)==formatDate(date,format))
        {
            return "今天";//formatDate(date,"HH:mm");
        }
        dev=fix(now-date,86400000,1);
        switch(true){
//                case dev>=365:
//                    return (ch[fix(dev,365,0)]||"n")+"年前";
//                case dev>182:
//                    return "半年前"
//                case dev>=30:
//                    return ch[fix(dev,30,0)]+"月前";
//                case dev>=7:
//                    return ch[fix(dev,7,0)]+"周前";
            case dev>=3:
                //return ch[dev]+"天前";
                return dev+"天前";
            case dev==2:
                return "前天";
            case dev==1:
                return "昨天";
            default:
                return "今天";//formatDate(date,"HH:mm");
        }
    }
    function formatDate(date, fmt) {
       date = date || new Date();
       var o = {
           "M+":date.getMonth() + 1, //月份
           "d+":date.getDate(), //日
           "h+":date.getHours() % 12 == 0 ? 12 : date.getHours() % 12, //小时
           "H+":date.getHours(), //小时
           "m+":date.getMinutes(), //分
           "s+":date.getSeconds(), //秒
           "q+":Math.floor((date.getMonth() + 3) / 3), //季度
           "S":date.getMilliseconds() //毫秒
       }, week = {
           "0":"\u65e5", "1":"\u4e00", "2":"\u4e8c", "3":"\u4e09", "4":"\u56db", "5":"\u4e94", "6":"\u516d"
       };
       fmt = fmt || "yyyy-MM-dd HH:mm:ss";
       if (/(y+)/.test(fmt)) {//年特殊处理
           fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
       }
       if (/(E+)/.test(fmt)) {//星期特殊处理
           fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "\u661f\u671f" : "\u5468") : "") + week[date.getDay() + ""]);
       }
       for (var k in o) {
           if (new RegExp("(" + k + ")").test(fmt)) {
               fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
           }
       }
       return fmt;
   }

   function formatTemplate(tmpl,data){
        return $.trim(tmpl.replace(/\{([\w\.]*)\}/g, function (str, key) {
            var keys = key.split("."), value = data[keys.shift()];
            while(keys.length>0&&value)
                value=value[keys.shift()];
            return (value === null || value === undefined) ? "" : value;
        }));
    }

    function loadTip(text,timer){
        minMessage.Show({
            text: text,
            type: "load",
            window:{ warp:$('.page#easynote-home')},
            timeout: timer||2000
        });
    }

    function infoTip(text,timer){
        minMessage.Show({
            text: text,
            type: "inf",
            window:{ warp:$('.page#easynote-home')},
            timeout: timer||2000
        });
    }

    function successTip(text,timer){
        minMessage.Show({
            text: text,
            type: "suc",
            window:{ warp:$('.page#easynote-home')},
            timeout: timer||2000
        });
    }

    function warningTip(text,timer){
        minMessage.Show({
            text: text,
            type: "war",
            window:{ warp:$('.page#easynote-home')},
            timeout: timer||2000
        });
    }

    minMessage = (function(){
        var _temp = '<div class="popup-hint" style="z-index:9999999999;"><i class="" rel="type"></i><em class="sl"><b></b></em><span rel="con"></span><em class="sr"><b></b></em></div>';
        var _cache = {
            Type: {
                suc: "hint-icon hint-suc-m",
                war: "hint-icon hint-war-m",
                err: "hint-icon hint-err-m",
                load: "hint-loader",
                inf: "hint-icon hint-inf-m"
            }
        },
        _dom,
        _timer;
        var create = function(text, type, w) {
            if (!_dom) {
                _dom = $(String.format(_temp, text));
                $(w).append(_dom)
            }
            _dom.find("[rel='con']").html(text);
            var icon = _dom.find("[rel='type']");
            for (var k in _cache.Type) {
                icon.removeClass(_cache.Type[k])
            }
            icon.addClass(_cache.Type[type])
        };
        var hide = function() {
            if (_timer) {
                window.clearTimeout(_timer)
            }
            if (_dom) {
                _dom.hide()
            }
        };
        return {
            Show: function(obj) {
                if (!obj.type) {
                    obj.type = "war"
                }
                create(obj.text, obj.type, obj.window ? obj.window.warp: false);
                Util.Layer.Center(_dom, {
                    Main: obj.window ? obj.window.warp: false
                });
                _dom.show();
                
            },
            Hide: function() {
                hide()
            }
        }
    })();
})(jQuery,window)